package com.kll.carolinehmibiz.presentation.presenter


import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import com.google.gson.Gson
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.base.utils.L
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.DownloadFileProgress
import com.kll.carolinehmibiz.net.bean.GetAppNewlyVersionResponse
import com.kll.carolinehmibiz.presentation.BasePresenter
import com.kll.carolinehmibiz.presentation.listener.SettingProtocol
import java.io.File

class SettingPresenter(context: Context, mView: SettingProtocol.IView): BasePresenter(context), SettingProtocol.IPresenter {
    private var mView: SettingProtocol.IView? = mView
    private var getAppNewlyVersionIsBusying = false
    private var downloadFileIsBusying = false

    override fun logout() {
        OperationManager.getInstancce().logout()
    }

    override fun getAppNewlyVersion() {
        if (getAppNewlyVersionIsBusying) return
        getAppNewlyVersionIsBusying = true
        OperationManager.getInstancce().getAppNewlyVersion(object: OperateListener {
            override fun onSuccess(state: Int, obj: Any?) {
                getAppNewlyVersionIsBusying = false
                if(obj != null) {
                    val versionInfo = obj as GetAppNewlyVersionResponse

                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                        mContext.packageManager.getPackageInfo(mContext.packageName, 0).versionCode
                    } else {
                        mContext.packageManager.getPackageInfo(mContext.packageName, 0).longVersionCode
                    }

                    L.d(">>>", "${versionInfo.versioncode}   ${getVersionCode()}")
                    if(versionInfo.versioncode > getVersionCode().toLong()) {
                        mView?.getAppNewlyVersionTrue(versionInfo)
                    } else {
                        mView?.getAppNewlyVersionFalse()
                    }
                }

            }

            override fun onFail(code: Int, message: String) {
                getAppNewlyVersionIsBusying = false
                mView?.getAppNewlyVersionFailed(code, message)
            }

        })
    }

    override fun downloadFile(url: String, savePath: String) {
        if (downloadFileIsBusying) return
        downloadFileIsBusying = true
        OperationManager.getInstancce().downloadFile(url, savePath, object: OperateListener {
            override fun onSuccess(state: Int, obj: Any?) {
                downloadFileIsBusying = false
                L.v(">>>>>>", "MyApplication>>onNewlyVersion>>onSuccess:: obj = ${Gson().toJson(obj)}")

                var data = obj as DownloadFileProgress

                mView?.downloadFileSuccessed(data, savePath)
            }

            override fun onFail(code: Int, message: String) {
                downloadFileIsBusying = false
                L.v(">>>>>>", "MyApplication>>onNewlyVersion>>onFail")
                mView?.downloadFileFailed(message)
            }

        })
    }

    /**
     * 获取当前版本号
     */
    private fun getVersionCode(): Int {
        try {
            val packageManager = mContext.packageManager
            val packageInfo = packageManager.getPackageInfo(mContext.packageName, 0)
            return packageInfo.versionCode
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    /**
     * 打开apk安装界面
     *
     * @param context
     * @param apkUri
     */
    override fun openInstallPage(apkPath: String) {

        L.v("----", "apkUri = ${apkPath}")

        try {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//            var uri: Uri

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                var uri = FileProvider.getUriForFile(mContext, "com.kll.tv.fileprovider", File(apkPath))
                intent.setDataAndType(uri, "application/vnd.android.package-archive")
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            } else {
                intent.setDataAndType(Uri.fromFile(File(apkPath)), "application/vnd.android.package-archive")
            }

            mContext.startActivity(intent)
        }catch (e: Exception ){
            e.printStackTrace()
        }
    }

}